package com.yc.thread;

/**
 * 线程的原子性
 *
 * 可见性、有序性
 */

public class ThreadSafeSample {
	public int sharedState;

	public void nonSafeAction() {
//		synchronized (this) {
		while (sharedState < 100000) {

				int former = sharedState ++;
				int latter = sharedState;

				if (former != latter -1) {
					System.out.println("Observed data race, former is " + former
							+ "," + " latter is " + latter);
				}
			}
//		}
	}

	public static void main(String[] args) throws Exception{
		ThreadSafeSample safeSample = new ThreadSafeSample();
		Thread threadA = new Thread() {
			public void run() {
				safeSample.nonSafeAction();
			}
		};

		Thread threadB = new Thread() {
			public void run() {
				safeSample.nonSafeAction();
			}
		};

		threadA.start();
		threadB.start();
		threadA.join();
		threadB.join();
	}
}
